package es.nadalgoyo.frikiquest.control;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import es.nadalgoyo.frikiquest.R;
import es.nadalgoyo.frikiquest.action.ActionCuestion;
import es.nadalgoyo.frikiquest.dispatcher.PreguntaDispatcher;
import es.nadalgoyo.frikiquest.util.Util;
import es.sergionadal.mvc.dispatcher.exception.DispatcherException;

public class PreguntaControl extends AbstractControl {

	private TextView txtView;

	public static final String IMAGEN = "imagen";

	private ImageView img;

	public PreguntaControl(Context context) {
		super(context);
	}

	public PreguntaControl(Context context, AttributeSet att) {
		super(context, att);
	}

	@Override
	public void inicializar() {
		String infService = Context.LAYOUT_INFLATER_SERVICE;
		LayoutInflater li = (LayoutInflater) getContext().getSystemService(
				infService);

		li.inflate(R.layout.pregunta, this, true);
		img = (ImageView) findViewById(R.id.ImgPregunta);
		img.setVisibility(INVISIBLE);
		byte[] imagen = getImagen();

		if (imagen != null) {
			img.setVisibility(VISIBLE);
			img.setImageBitmap(BitmapFactory.decodeByteArray(imagen, 0,
					imagen.length));
			img.setMaxHeight(50);
			img.setMaxWidth(50);
			img.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Bundle bundle = new Bundle();
					bundle.putByteArray(IMAGEN, getImagen());
					PreguntaDispatcher cuesDis = new PreguntaDispatcher(
							getActivity(), bundle,
							PreguntaDispatcher.PREGUNTA_IMG);
					try {
						cuesDis.dispatch(false);
					} catch (DispatcherException e) {
						e.printStackTrace();
						Util.showErrorMensaje(getActivity(), e.getMessage(),
								true);
					}
				}
			});
		}

		txtView = (TextView) findViewById(R.id.TxtPregunta);
		txtView.setText(getText());
	}

	/*
	 * public void setImageResoruce(int id) { idImage = id;
	 * img.setImageResource(idImage); img.setMaxHeight(50); img.setMaxWidth(50);
	 * }
	 */

	public void setFontText(Typeface typeface) {
		txtView.setTypeface(typeface);
	}

	/*
	 * private File getImgfile (){ return new File
	 * ("D:\\WORKSPACE75\\Android\\FrikiTrivial\\res\\drawable-mdpi\\gato_small.jpg"
	 * ); }
	 */

	private String getText() {
		return getActivity().getIntent().getExtras()
				.getString(ActionCuestion.ID_PREGUNTA);
	}

	private byte[] getImagen() {
		return getActivity().getIntent().getExtras()
				.getByteArray(ActionCuestion.IMAGEN);
	}

	public int getPuntos() {
		return getActivity().getIntent().getExtras()
				.getInt(ActionCuestion.PUNTOS_PREGUNTA);
	}
}